package com.wangzhy.common.util;

import com.wangzhy.config.DownloadConfig;
import com.wangzhy.spider.vo.ImgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ：wangzy
 * @date ：  2021/9/16 9:22
 * @description： 下载
 */
@Component
public class DownloadUtil {

    @Autowired
    private  DownloadConfig downloadConfig;

    private static DownloadUtil downloadUtil;

    @PostConstruct
    public void init(){
        downloadUtil = this;
        downloadConfig = this.downloadConfig;
    }

    public static ExecutorService pool = Executors.newFixedThreadPool(10);

    public static void downloadImgs(List<ImgVo> imgList)  {
        DownloadConfig downloadConfig1 = new DownloadConfig();
        for (ImgVo imgVo : imgList) {
            String imgUrl = imgVo.getImgUrl();
            if(imgVo.getImgUrl().startsWith("/health-mall/")){
                String fileName = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
                String fileDir = imgUrl.substring(0,imgUrl.lastIndexOf("/"));
                // 创建文件夹
                pool.execute(new DownloadTask(downloadUtil.downloadConfig.getImgPrefix()+imgUrl, downloadUtil.downloadConfig.getDownloadPath() +fileDir));
            }
        }
    }

    public static void main(String[] args) {
        DownloadTask task = new DownloadTask("https://images.expowh.com/health-mall/dev/20210615/ea890a3d9900474182dcfe2374da8036.jpg"
                ,"D:\\WANGZHY/health-mall/dev/20210615/"
        );
        task.run();
    }
}
